package com.hht.kotlineee.net


import com.hht.kotlineee.Constant
import com.hht.kotlineee.MyApplication
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

object HttpCreate {

    private val builder = Retrofit.Builder()
        .baseUrl(Constant.BASE_URL)
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .client(provideOKHttpClient())
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())

    fun create(): HttpServerApi = builder.build().create(HttpServerApi::class.java)

    private fun provideOKHttpClient(): OkHttpClient {
        val loggingInterceptor = HttpLoggingInterceptor(RxHttpLoggerInterceptor())
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        val builder = OkHttpClient.Builder()
            //设置缓存配置 缓存最大10M
            .cache(Cache(File(MyApplication.INSTANCE.cacheDir, "cxk_cache"), 10 * 1024 * 1024))
            //设置连接超时时间
            .connectTimeout(Constant.NETWORK_CONNECT_TIME_OUT.toLong(),TimeUnit.SECONDS)
            .readTimeout(Constant.NETWORK_CONNECT_TIME_OUT.toLong(),TimeUnit.SECONDS)
            .writeTimeout(Constant.NETWORK_CONNECT_TIME_OUT.toLong(), TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            //配置工厂监听器。主要是计算网络过程消耗时间
//            .eventListenerFactory(NetworkListener.get())
            .addInterceptor(HeaderInterceptor())
            .addInterceptor(loggingInterceptor)

        return builder.build()
    }

    class HeaderInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val original = chain.request()
            val request = original.newBuilder().apply {
                header("Content-type","application/json; charset=utf-8")
                header("User-Agent", System.getProperty("http.agent") ?: "unknown")
            }.build()
            return chain.proceed(request)
        }
    }
}